import uuid
from fastapi import APIRouter, Depends, UploadFile, Form, File, HTTPException
from pathlib import Path
from sqlalchemy.orm import Session
from typing import Optional

from app.services.v2 import create_harp_service, update_harp, get_harp_with_id, get_all_harps
from app.utils.setting import Settings

settings = Settings()

from app.db.database import get_db
from app.models.harp import Harps
from app.schemas.harp_schemas import create_harp, harp_update

router = APIRouter(prefix="/api/v2", tags=["harp"])


@router.get("/all/harps")
def get_all(db: Session = Depends(get_db)):
    return get_all_harps(db)


@router.get("/harp/{id}")
def get_harp(id: int, db: Session = Depends(get_db)):
    return get_harp_with_id(id, db)


@router.post("/add/harp")
async def register_new_harp(
        harp_name: str = Form(...),
        harp_type: str = Form(...),
        harp_desc: str = Form(...),
        audio_url: UploadFile = File(...),
        is_bax: Optional[str] = Form("false"),  # 默认false
        db: Session = Depends(get_db)
):
    try:
        file_ext = Path(audio_url.filename).suffix
        unique_filename = f"{uuid.uuid4()}{file_ext}"
        file_location = settings.upload_harp_dir / unique_filename

        # 保存文件
        with open(file_location, "wb+") as file_object:
            file_object.write(audio_url.file.read())

        # 使用实例化的 settings 而非类
        relative_path = f"{settings.base_url}/uploads/harp/{unique_filename}"

        harp_data = {
            "harp_name": harp_name,
            "harp_type": harp_type,
            "harp_desc": harp_desc,
            "audio_url": relative_path,
            "is_bax": is_bax.lower() == "true"
        }
        return await create_harp_service(db, harp_data)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")


# 更新路由保持不变
@router.put("/update/harp/{id}")
async def update_harp_endpoint(
        id: int,
        harp_name: str = Form(...),
        harp_type: str = Form(...),
        harp_desc: str = Form(...),
        audio_url: Optional[UploadFile] = File(None),
        is_bax: str = Form("false"),
        db: Session = Depends(get_db)
):
    return await update_harp(
        id=id,
        harp_name=harp_name,
        harp_type=harp_type,
        harp_desc=harp_desc,
        audio_url=audio_url,
        is_bax=is_bax,
        db=db,

    )
